<template>
  <div class="login-container">
    <span class="form-title">后台管理系统</span>
    <div class="form-container">
      <el-form ref="form" :model="form" :rules="rules" label-suffix="：" label-width="70px">
        <el-form-item label="账号" prop="email">
          <el-input v-model="form.account" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="submit-btn" type="primary" @click="onSubmit">登录</el-button>
        </el-form-item>
      </el-form>
      <div class="tips">
        <span>还没有账号？现在<router-link to="/register">注册</router-link></span>
      </div>
    </div>
  </div>
</template>

<script>
import { userLogin } from '@/api/user'

export default {
  name: 'LoginView',
  data () {
    return {
      form: {
        account: '',
        password: ''
      },
      rules: {
        account: [
          {
            required: true,
            message: '请输入账号',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 30,
            message: '密码长度要求6-30个字符之间',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    onSubmit () {
      this.$refs.form.validate((valid) => {
        // 判断校验失败的情况
        if (!valid) {
          this.$notify.error({
            title: '错误',
            message: '校验不通过'
          })
          return
        }
        const data = {
          account: this.form.account,
          password: this.form.password
        }

        userLogin(data).then(res => {
          const {
            code,
            msg,
            token,
            role
          } = res
          if (code !== 0) {
            return this.$message.error(msg)
          }
          console.log(token)
          // 只允许存放字符串
          localStorage.setItem('node-token', token)
          localStorage.setItem('role', role)
          this.$router.push('/')
        })
          .catch(err => {
            console.log(err)
          })
      })
    }
  }
}
</script>

<!--scoped 的意思是只在当前vue文件有效-->
<style scoped>
.login-container {
  position: relative;
  height: 100%;
  width: 100%;
  background: url("@/assets/bg.jpg") no-repeat center center;
  background-size: 100% 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.form-title {
  margin: 15px;
  font-size: 24px;
  color: #333;
  font-weight: 700;
}

.submit-btn {
  width: 90%;
}

.form-container {
  height: 200px;
  width: 300px;
  background: #ffff;
  border-radius: 10px;
  padding: 20px;
}

.tips {
  font-size: 12px;
  text-align: right;
  color: #333;
}

.tips span a {
  margin: 0 2px;
  color: #409eff;
}
</style>
